﻿using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Microsoft.Extensions.Options;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Serialization;
using System;
using System.Collections.Generic;
using TomNet.Core.Options;
using TomNet.QRCoder;


namespace TomNet.Core
{
    public static class ServiceCollectionExtensions
    {
        public static IServiceCollection AddBase(this IServiceCollection services, bool qrcode = false)
        {

            #region 如果替换掉默认的OpResult，使用框架内提供的OpReslt时，请打开注释
            // Json Default Settings 
            JsonConvert.DefaultSettings = new Func<JsonSerializerSettings>(() =>
            {
                var setting = new JsonSerializerSettings
                {
                    //ContractResolver = new DefaultContractResolver(),
                    // 修改属性名称的序列化方式，首字母小写，即驼峰样式
                    ContractResolver = new CamelCasePropertyNamesContractResolver(),

                    // 日期类型默认格式化处理
                    DateFormatHandling = Newtonsoft.Json.DateFormatHandling.MicrosoftDateFormat,
                    DateFormatString = "yyyy/MM/dd HH:mm:ss",

                    // 忽略循环引用
                    ReferenceLoopHandling = ReferenceLoopHandling.Ignore,

                    // 空值处理
                    //NullValueHandling = NullValueHandling.Ignore
                };
                return setting;
            });
            #endregion

            if (qrcode) services.AddTransient<IQRCodeService, QRCodeService>();
            services.TryAddSingleton<IConfigureOptions<TomNetOptions>, TomNetOptionsSetup>();
            return services;
        }
        public static IServiceCollection AddSetting<T>(this IServiceCollection services, string path) where T : class, new()
        {
            T setting = SettingsReader.LoadSetting<T>(path);
            services.TryAddSingleton(setting);
            return services;
        }

    }
}
